package com.youlai.system.common.util;

import com.youlai.system.model.vo.DataLogsVO;
import org.apache.commons.math3.stat.regression.SimpleRegression;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/*
数据预测 1 分钟后
数据类型
 List<DataLogsVO>
{"time":"2024-05-06 16:55:27","value":175.83333333333334}
 */
public class TensorFlow {

    private static final DateTimeFormatter CUSTOM_DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public static List<DataLogsVO> comForecast(List<DataLogsVO> dataLogsVOList) {
        if (dataLogsVOList == null || dataLogsVOList.isEmpty()) {
            throw new IllegalArgumentException("输入的数据列表不能为空");
        }

        // 解析输入的 DataLogsVO 列表
        int size = dataLogsVOList.size();
        double[] times = new double[size];
        double[] datas = new double[size];

        // 获取第一个时间点
        LocalDateTime firstTime = LocalDateTime.parse(dataLogsVOList.get(0).getTime(), CUSTOM_DATE_TIME_FORMATTER);

        // 解析时间戳和数据值
        for (int i = 0; i < size; i++) {
            DataLogsVO item = dataLogsVOList.get(i);
            LocalDateTime time = LocalDateTime.parse(item.getTime(), CUSTOM_DATE_TIME_FORMATTER);
            Duration diff = Duration.between(firstTime, time);
            times[i] = diff.getSeconds();
            datas[i] = item.getValue();
        }

        // 创建线性回归模型
        SimpleRegression regression = new SimpleRegression();
        for (int i = 0; i < size; i++) {
            regression.addData(times[i], datas[i]);
        }

        // 预测未来一小时内的数据
        List<DataLogsVO> outputList = new ArrayList<>();
        int futureSeconds = 60; // 一个小时有3600秒
        for (int i = 1; i <= futureSeconds; i++) {
            double nextTime = times[size - 1] + i; // 从最后一个时间点开始增加
            double nextData = regression.predict(nextTime);

            // 构造预测结果的 DataLogsVO 对象
            LocalDateTime nextTimeLocalDateTime = firstTime.plusSeconds((long) nextTime);
            DataLogsVO prediction = new DataLogsVO();
            // 格式化 value，保留一位小数
            prediction.setTime(nextTimeLocalDateTime.format(CUSTOM_DATE_TIME_FORMATTER));
            prediction.setValue((float) Math.round(nextData * 10) / 10);
            outputList.add(prediction);
        }

        return outputList;
    }



}
